//
//  PicSelectController.m
//  WestWolves
//
//  Created by JL on 16/1/3.
//  Copyright © 2016年 ZJ. All rights reserved.
//

#import "PicSelectController.h"
#import <AVFoundation/AVFoundation.h>
#import "UIAlertController+AlertController.h"

@interface PicSelectController ()

@end

@implementation PicSelectController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)selectImaWithType:(PickerControllerSourceType)type//1，2，3  小视频，拍照，相册
{
    UIImagePickerControllerSourceType sourceType ;
    if (type==PickerAlbumSourceType) {
        if ([self canOpenPhotoLibrary]){
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }else{
            return;
        }
    }else {
        if ([self canOpenCamera]){
            sourceType = UIImagePickerControllerSourceTypeCamera;
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的设备的拍照功能不可用" preferredStyle:UIAlertControllerStyleAlert andCancelAction:^{
                
            } andOtherAction:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [self presentViewController:alert animated:YES completion:nil];
            return;
        }
    }
    UIImagePickerController* imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing = YES;
    imagePicker.sourceType = sourceType;
    if (type==PickerVideoSourceType) {
        imagePicker.videoQuality = UIImagePickerControllerQualityTypeMedium;
        imagePicker.videoMaximumDuration = 30.0f;
        NSArray* availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        imagePicker.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];
//        // 摄像头, 这里设置默认使用后置摄像头
//        imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
//        // 摄像头模式, 这里设置为录像模式
//        imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
        // 录像质量,高质量拍照，再低质量压缩
        imagePicker.videoQuality = UIImagePickerControllerQualityTypeHigh;
        
    }
    [self presentViewController:imagePicker animated:YES completion:nil];
}
- (void)assetPickerSelectIma:(int)imaNum
{
    ZYQAssetPickerController * picker=[[ZYQAssetPickerController alloc] init];
    picker.delegate=self;
    picker.maximumNumberOfSelection = imaNum;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = NO;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject,NSDictionary *bindings){
        if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType]isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration]doubleValue];
            return duration >= 5;
        }else{
            return  YES;
        }
    }];
    [self presentViewController:picker animated:YES completion:nil];
    
}

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //UIImage * ima = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    NSURL *url=nil;
    int type=0;
    if ([info objectForKey:UIImagePickerControllerMediaURL]) {
        url = [info objectForKey:UIImagePickerControllerMediaURL];
        BOOL compatible = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([url path]);
        if (compatible)
        {
            UISaveVideoAtPathToSavedPhotosAlbum([url path], self, nil, NULL);
        }
        //小视频
        type=1;
    }else{
        if(picker.sourceType==UIImagePickerControllerSourceTypeCamera){
            type=2;
        }else if (picker.sourceType==UIImagePickerControllerSourceTypePhotoLibrary){
            type=3;
        }
    }
    if (type==0) {
        return;
    }
    [self finishImagePickerController:picker didFinishPickingMediaWithInfo:info andType:type andMediaURL:url];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self failImagePickerControllerDidCancel:picker];
}
//确定
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    NSMutableArray *picArray=[[NSMutableArray alloc] init];
    for (int i=0;i<assets.count;i++) {
        ALAsset *asset=assets[i];
        UIImage *ima=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [picArray addObject:ima];
    }
    [self finishAssetPickerController:picker didFinishPickingAssets:picArray];
}
//取消
- (void)assetPickerControllerDidCancel:(ZYQAssetPickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self failImagePickerControllerDidCancel:picker];
}

- (void)finishImagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info andType:(PickerControllerSourceType)type andMediaURL:(NSURL *)url
{

}
- (void)failImagePickerControllerDidCancel:(UINavigationController*)picker
{
    
}
- (void)finishAssetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSMutableArray *)picArray
{
    
}


- (NSString *) changeVideoToMap4WithVideoURL:(NSURL *)url
{
    NSString *_mp4Path = nil;
    
    NSString *path=[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output"];
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if (![ fileManager fileExistsAtPath:path]) {
        NSError *error=nil;
        [fileManager removeItemAtPath:path error:&error];
        [fileManager createDirectoryAtURL:[NSURL fileURLWithPath:path] withIntermediateDirectories:YES attributes:nil error:&error];
    }
    
    NSString *mp4Quality=AVAssetExportPresetHighestQuality;
    if (!url)
    {
//        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"错误"
//                                                         message:@"Please record a video first"
//                                                        delegate:nil
//                                               cancelButtonTitle:@"OK"
//                                               otherButtonTitles: nil];
//        [alert show];
        return nil;
    }
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    if ([compatiblePresets containsObject:mp4Quality]){
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:mp4Quality];
        NSDateFormatter* formater = [[NSDateFormatter alloc] init];
        [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
        _mp4Path = [path stringByAppendingFormat:@"%@.mp4", [formater stringFromDate:[NSDate date]]];
        exportSession.outputURL = [NSURL fileURLWithPath:_mp4Path];
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed:
                {
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Error"
//                                                           message:[[exportSession error] localizedDescription]
//                                                          delegate:nil
//                                                 cancelButtonTitle:@"OK"
//                                                 otherButtonTitles: nil];
//                        [alert show];
//                    });
                    break;
                }
                case AVAssetExportSessionStatusCancelled:
                {
                    break;
                }
                case AVAssetExportSessionStatusCompleted:
//                    NSLog(@"Successful!%@",_mp4Path);
                    
                    break;
                default:
                    break;
            }
        }];
    }else{
//        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error"
//                                                        message:@"AVAsset doesn't support mp4 quality"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"OK"
//                                              otherButtonTitles: nil];
//        [alert show];
    }
    
    [self removeVideoWithVideoPath:url.path];
    return _mp4Path;
}
- (BOOL)removeVideoWithVideoPath:(NSString *)path
{
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager isExecutableFileAtPath:path]) {
        NSError * error ;
        [fileManager removeItemAtPath:path error:&error];
        if (error) {
            return NO;
        }
    }else{
        return NO;
    }
    return YES;
}


- (UIImage *) getVideoImaWithUrl:(NSURL *)url
{
    AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:url options:nil];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
    generator.appliesPreferredTrackTransform = YES;
    generator.maximumSize = CGSizeMake(200, 150);
    NSError *error = nil;
    CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(1, 60) actualTime:NULL error:&error];
    UIImage* image = [UIImage imageWithCGImage:img];
    return image;
}
- (BOOL)canOpenCamera{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
- (BOOL)canOpenPhotoLibrary
{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
}

@end
